﻿using System.Runtime.CompilerServices;
using System.Threading;

namespace eLoop;

public abstract class ADefaultAllotter : ISchedulerAllotter
{
    private int schedulerIndex;

    protected abstract ITaskScheduler[] Schedulers
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        get;
    }

    public int Count
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        get { return this.Schedulers.Length; }
    }

    public ITaskScheduler Next()
    {
        var scheduler = this.Schedulers[this.schedulerIndex];
        this.schedulerIndex = Interlocked.Increment(ref this.schedulerIndex) % this.Count;
        return scheduler;
    }

    public void Shutdown()
    {
        for (int i = 0; i < this.Schedulers.Length; i++)
        {
            this.Schedulers[i].Dispose();
        }
    }
}